package com.gjs.sso.config.security.oauth;

import com.gjs.common.microservice.api.IUserMicroService;
import com.gjs.common.pojo.dto.user.UserInfoDTO;
import com.gjs.common.pojo.dto.user.UserQueryDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenEnhancer implements TokenEnhancer {

    @DubboReference
    private IUserMicroService userMicroService;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        // 通过微服务查询用户信息
        String username = ((User) authentication.getPrincipal()).getUsername();
        UserQueryDTO queryDTO = new UserQueryDTO();
        queryDTO.setUserAccount(username);
        UserInfoDTO userInfoDTO = userMicroService.getOne(queryDTO);
        // Token额外信息
        Map<String, Object> info = new HashMap<>();
        info.put("user_sn", userInfoDTO.getUserSn());
        // 把Token额外信息注入
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }

}

